﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.AuthorizeRBAC;
using RedDragon.Common.Dtos;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.RBAC.ErrorCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace RedDragon.RBAC.API.Application.Common.Role
{
    /// <summary>
    /// 角色显示Handler
    /// </summary>
    public class SearchRolesHandler : IRequestHandler<SearchRolesCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 角色表仓储
        /// </summary>
        public readonly IBaseRepository<Roles> rolesrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchRolesHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="rolesrepository"></param>
        /// <param name="logger"></param>
        public SearchRolesHandler(IMapper mapper, IBaseRepository<Roles> rolesrepository, ILogger<SearchRolesHandler> logger)
        {
            this.mapper = mapper;
            this.rolesrepository = rolesrepository;
            this.logger = logger;
        }

        /// <summary>
        /// 角色显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(SearchRolesCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() {Code=(int)CommonErrorCode.Success};
            try
            {
                var role =  await(await rolesrepository.GetAll()).ToListAsync();
                //权限编号模糊查
                if (!string.IsNullOrEmpty(request.RolesName))
                {
                    role = role.Where(x=>x.RolesName.Contains(request.RolesName)).ToList();
                }
              
                result.Data = role;
                result.Msg = "角色显示成功";
            }
            catch (Exception ex)
            {
                result.Msg = "角色显示失败" + ex.Message;
                logger.LogError("角色显示失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
